package com.learning.springmvc.advance.valid;

import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: ControllerAdvice
 * Description:
 * Date: 2019/5/22 15:12 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@ControllerAdvice
public class ControllerAopAdvice {

    /**
     * 全局异常捕捉处理
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Map<String, Object> errorHandler(Exception ex) {
        Map<String, Object> map = new HashMap<>(8);
        map.put("code", 100);
        map.put("msg", ex.getMessage());
        return map;
    }

    /**
     * 方法参数校验异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    public Map<String, Object> constraintViolationException(Exception e) {
        Map<String, Object> map = new HashMap<>(8);
        map.put("code", 101);
        map.put("msg", e.getMessage());
        return map;
    }


    /**
     * Bean 校验异常
     *
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Map<String, Object> notValidExceptionHandler(MethodArgumentNotValidException e) {
        Map<String, Object> map = new HashMap<>(8);
        map.put("code", 102);
        map.put("msg", e.getMessage());
        return map;
    }
}
